/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.system.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.cache.DictCache;
import org.springblade.common.utils.CommonUtil;
import org.springblade.common.utils.PoiExcelUtil;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.modules.admin.entity.MaintainPlanContentUser;
import org.springblade.modules.admin.entity.UserElevatorBrand;
import org.springblade.modules.admin.entity.UserElevatorSkill;
import org.springblade.modules.admin.entity.UserExt;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.UserCertVO;
import org.springblade.modules.admin.vo.user.UserStatusVo;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserBusinessSet;
import org.springblade.modules.system.enums.UserBusinessSetKeyEnum;
import org.springblade.modules.system.enums.UserBusinessSetValueEnum;
import org.springblade.modules.system.excel.UserExcel;
import org.springblade.modules.system.excel.UserImporter;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.service.UserBusinessSetService;
import org.springblade.modules.system.vo.UserVO;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static org.springblade.core.cache.constant.CacheConstant.USER_CACHE;

/**
 * 控制器
 *
 * @author Chill
 */
@NonDS
//@ApiIgnore
@RestController
@RequestMapping(AppConstant.APPLICATION_USER_NAME)
@AllArgsConstructor
public class UserController {

	private final IUserService userService;
	private final BladeRedis bladeRedis;
	private final UserExtService userExtService;
	private final UserCertService userCertService;
	private final UserBusinessSetService userBusinessSetService;
	private final IMaintainPlanContentUserService maintainPlanContentUserService;
	private final IUserElevatorBrandService userElevatorBrandService;
	private final IUserElevatorSkillService userElevatorSkillService;


	@GetMapping("getUserListOfRoleCode")
	@ApiOperation("只获取管理员")
	public R<List<User>> getUserListOfRoleCode(String roleCode, String tenantId) {
		List<Long> ids = userService.getUserByRoleName(tenantId, roleCode);
		List<User> users = userService.listByIds(ids);
		return R.data(users);
	}


	/**
	 * 查询单条
	 */
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "查看详情", notes = "传入id")
	@GetMapping("/detail")
	public R<UserVO> detail(User user) {
		User detail = userService.getOne(Condition.getQueryWrapper(user));
		UserVO userVO = UserWrapper.build().entityVO(detail);
		UserExt userExt = userExtService.getOne(Wrappers.<UserExt>lambdaQuery().eq(UserExt::getUserId, user.getId()));
		List<UserCertVO> userCerts = userCertService.selectListByUserId(user.getId());
		userVO.setUserCertDetails(userCerts);
		if (ObjectUtil.isNotEmpty(userExt)) {
			userVO.setAddress(userExt.getAddress());
			userVO.setLatitude(userExt.getLatitude());
			userVO.setLongitude(userExt.getLongitude());
			userVO.setVehicle(userExt.getVehicle());
			if (ObjectUtil.isNotEmpty(userExt.getVehicle())) {
				userVO.setVehicleName(DictCache.getValue("vehicle", userExt.getVehicle()));
			}
			userVO.setShowInfo(userExt.getShowInfo());
			userVO.setSubCom(userExt.getSubCom());
			userVO.setLocation(userExt.getLocation());
		}
		userVO.setCheckContentAll(UserBusinessSetValueEnum.CHECK_CONTENT_ALL_OFF.getValue());
		UserBusinessSet userBusinessSet = userBusinessSetService.getOne(Wrappers.<UserBusinessSet>lambdaQuery().eq(UserBusinessSet::getUserId, user.getId()).eq(UserBusinessSet::getConfigKey, UserBusinessSetKeyEnum.CHECK_CONTENT_ALL.getType()));
		if (ObjectUtil.isNotEmpty(userBusinessSet)) {
			userVO.setCheckContentAll(userBusinessSet.getConfigValue());
		}

		List<UserElevatorBrand> elevatorBrandList = userElevatorBrandService.list(Wrappers.<UserElevatorBrand>lambdaQuery().eq(UserElevatorBrand::getUserId, user.getId()));
		List<UserElevatorSkill> elevatorSkillList = userElevatorSkillService.list(Wrappers.<UserElevatorSkill>lambdaQuery().eq(UserElevatorSkill::getUserId, user.getId()));
		userVO.setUserElevatorBrandIds(elevatorBrandList.stream().map(UserElevatorBrand::getBrandId).collect(Collectors.toList()));
		userVO.setUserElevatorSkillIds(elevatorSkillList.stream().map(UserElevatorSkill::getSkillId).collect(Collectors.toList()));
		return R.data(userVO);
	}

	/**
	 * 查询单条
	 */
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "查看详情", notes = "传入id")
	@GetMapping("/info")
	public R<UserVO> info(BladeUser user) {
		User detail = userService.getById(user.getUserId());
		return R.data(UserWrapper.build().entityVO(detail));
	}

	/**
	 * 用户列表
	 */
	@GetMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "列表", notes = "传入account和realName")
	@PreAuth("hasPermission('user:list') or hasAnyRole('administrator','admin')")
	public R<IPage<UserVO>> list(@ApiIgnore @RequestParam Map<String, Object> user, Query query, BladeUser bladeUser) {
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
		IPage<User> pages = userService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(User::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(UserWrapper.build().pageVO(pages));
	}

	/**
	 * 自定义用户列表
	 */
	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "phone", value = "手机号", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "列表", notes = "传入account和realName")
	@PreAuth("hasPermission('user:page') or hasAnyRole('administrator','admin')")
	public R<IPage<UserVO>> page(@ApiIgnore User user, Query query, Long deptId, BladeUser bladeUser) {
		IPage<User> pages = userService.selectUserPage(Condition.getPage(query), user, deptId, (bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? StringPool.EMPTY : bladeUser.getTenantId()));
		return R.data(UserWrapper.build().pageVO(pages));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增或修改", notes = "传入User")
	@PreAuth("hasPermission('user:submit') or hasAnyRole('administrator','admin')")
	public R submit(@Valid @RequestBody User user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.submit(user));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入User")
	public R update(@Valid @RequestBody User user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.updateUser(user));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "删除", notes = "传入id集合")
	@PreAuth("hasPermission('user:remove') or hasAnyRole('administrator','admin')")
	public R remove(@RequestParam String ids) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.removeUser(ids));
	}

	/**
	 * 设置菜单权限
	 */
	@PostMapping("/grant")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "权限设置", notes = "传入roleId集合以及menuId集合")
	@PreAuth("hasPermission('user:grant') or hasAnyRole('administrator','admin')")
	public R grant(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds,
				   @ApiParam(value = "roleId集合", required = true) @RequestParam String roleIds) {
		boolean temp = userService.grant(userIds, roleIds);
		return R.status(temp);
	}

	/**
	 * 重置密码
	 */
	@PostMapping("/reset-password")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "初始化密码", notes = "传入userId集合")
	@PreAuth("hasPermission('user:reset:password') or hasAnyRole('administrator','admin')")
	public R resetPassword(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds) {
		boolean temp = userService.resetPassword(userIds);
		return R.status(temp);
	}

	/**
	 * 修改密码
	 */
	@PostMapping("/update-password")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "修改密码", notes = "传入密码")
	public R updatePassword(BladeUser user, @ApiParam(value = "旧密码", required = true) @RequestParam String oldPassword,
							@ApiParam(value = "新密码", required = true) @RequestParam String newPassword,
							@ApiParam(value = "新密码", required = true) @RequestParam String newPassword1) {
		boolean temp = userService.updatePassword(user.getUserId(), oldPassword, newPassword, newPassword1);
		return R.status(temp);
	}

	/**
	 * 修改基本信息
	 */
	@PostMapping("/update-info")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "修改基本信息", notes = "传入User")
	public R updateInfo(@Valid @RequestBody User user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.updateUserInfo(user));
	}

	/**
	 * 用户列表
	 *
	 * @param isSign 是否只要考勤人员，默认false 全部
	 */
	@GetMapping("/user-list")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "用户列表", notes = "传入user")
	public R<List<User>> userList(User user, BladeUser bladeUser, Long planId, @RequestParam(defaultValue = "false") Boolean isSign) {
		bladeUser.setTenantId(AuthUtil.getTenantId());
		List<User> list = userService.list(user, bladeUser, isSign);
		if (planId != null) {
			List<MaintainPlanContentUser> contentUserList = maintainPlanContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, planId));
			if (contentUserList.size() > 0) {
				List<Long> userIds = contentUserList.stream().map(MaintainPlanContentUser::getUserId).collect(Collectors.toList());
				for (User user1 : list) {
					if (userIds.contains(user1.getId())) {
						user1.setDisabled(true);
					}
				}
			}
		}
		return R.data(list);
	}


	/**
	 * 用户列表
	 */
	@GetMapping("/user-list/v2")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "用户列表", notes = "传入user")
	public R<List<User>> userList(String deptIds) {
		if (StrUtil.isEmpty(deptIds)) {
			return R.data(userService.list());
		}
		List<String> list1 = Arrays.asList(deptIds.split(","));
		List<User> resultList = new ArrayList<>(16);
		for (String str : list1) {
			List<User> list = userService.list(Wrappers.<User>lambdaQuery().like(User::getDeptId, str));
			resultList.addAll(list);
		}
		return R.data(resultList);
	}

	/**
	 * 导入用户
	 */
	@PostMapping("import-user")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "导入用户", notes = "传入excel")
	public R importUser(MultipartFile file, Integer isCovered) {
		UserImporter userImporter = new UserImporter(userService, isCovered == 1);
		ExcelUtil.save(file, userImporter, UserExcel.class);
		return R.success("操作成功");
	}

	/**
	 * 导出用户
	 */
	@GetMapping("export-user")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "导出用户", notes = "传入user")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public void exportUser(@RequestParam Map<String, Object> user, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
		if (!AuthUtil.isAdministrator()) {
			queryWrapper.lambda().eq(User::getTenantId, bladeUser.getTenantId());
		}
		queryWrapper.lambda().eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<UserExcel> list = userService.exportUser(queryWrapper);
		ExcelUtil.export(response, "用户数据" + DateUtil.time(), "用户数据表", list, UserExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<UserExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "用户数据模板", "用户数据表", list, UserExcel.class);
	}


	/**
	 * 第三方注册用户
	 */
	@PostMapping("/register-guest")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "第三方注册用户", notes = "传入user")
	public R registerGuest(User user, Long oauthId) {
		return R.status(userService.registerGuest(user, oauthId));
	}

	/**
	 * 配置用户平台信息
	 */
	@PostMapping("/update-platform")
	@ApiOperationSupport(order = 16)
	@ApiOperation(value = "配置用户平台信息", notes = "传入user")
	public R updatePlatform(Long userId, Integer userType, String userExt) {
		return R.status(userService.updatePlatform(userId, userType, userExt));
	}

	/**
	 * 查看平台详情
	 */
	@ApiOperationSupport(order = 17)
	@ApiOperation(value = "查看平台详情", notes = "传入id")
	@GetMapping("/platform-detail")
	@PreAuth("hasPermission('user:platform:detail') or hasAnyRole('administrator','admin')")
	public R<UserVO> platformDetail(User user) {
		return R.data(userService.platformDetail(user));
	}


	/**
	 * 用户列表查询
	 */
	@ApiImplicitParams({
		@ApiImplicitParam(name = "name", value = "人员姓名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "deptName", value = "部门名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "postName", value = "职位名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "current", value = "当前页数", paramType = "query", dataType = "int"),
		@ApiImplicitParam(name = "size", value = "每页数量", paramType = "query", dataType = "int")
	})
	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "用户列表查询", notes = "用户列表查询")
	@GetMapping("/search/user")
	public R<IPage<UserVO>> userSearch(@ApiIgnore UserVO user, @ApiIgnore Query query) {
		return R.data(userService.selectUserSearch(user, query));
	}

	/**
	 * 用户解锁
	 */
	@PostMapping("/unlock")
	@ApiOperationSupport(order = 19)
	@ApiOperation(value = "账号解锁", notes = "传入id")
	public R unlock(String userIds) {
		List<User> userList = userService.list(Wrappers.<User>lambdaQuery().in(User::getId, Func.toLongList(userIds)));
		userList.forEach(user -> bladeRedis.del(CacheNames.tenantKey(user.getTenantId(), CacheNames.USER_FAIL_KEY, user.getAccount())));
		return R.success("操作成功");
	}

	/**
	 * 获取用户部分字典数据
	 *
	 * @param key
	 * @return
	 */
	@GetMapping("/user/dict")
	public R<List<Dict>> selectUserDict(String key) {
		return R.data(DictCache.getList(key));
	}

	/**
	 * 获取在职离职的统计
	 *
	 * @return 数据集
	 */
	@GetMapping("/getUserStatusList")
	@ApiOperation("获取用户在职离职的数量统计")
	public R<List<UserStatusVo>> getUserStatusList() {
		return R.data(userService.getUserStatusList());
	}

	/**
	 * 批量更新人员部门
	 */
	@PostMapping("/update/dept/batch")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "批量更新人员部门", notes = "批量更新人员部门")
	public R<Boolean> updateDeptBatch(@RequestBody List<User> userList) {
		return R.data(userService.updateDeptBatch(userList));
	}

	@ApiOperation("下载人员模板")
	@PostMapping("/down/template")
	public void downElevatorTemplate(HttpServletResponse response, Integer level) {
		userService.downElevatorTemplate(response, level);
	}

	@ApiOperation("导入人员数据")
	@PostMapping("/upload/excel")
	public R<Map<String, Object>> uploadElevatorTemplate(@RequestParam("file") MultipartFile file, @RequestParam("level") Integer level, @RequestParam Integer temp) throws IOException {
		if (file.isEmpty()) {
			return R.fail("上传文件不能为空");
		}

		Workbook wb = null;
		try {
			wb = WorkbookFactory.create(file.getInputStream());
		} catch (InvalidFormatException e) {
			return R.fail("请使用正确的人员模板导入电梯");
		}
		Sheet sheet = wb.getSheetAt(0);

		List<Map<String, Object>> readAll = PoiExcelUtil.readExcel(wb, 0, 1, 2, 0);
		if (readAll.size() == 0) {
			return R.fail("上传文件不能为空");
		}

		Map<String, Object> resultMap = userService.uploadExcel(readAll, level, temp);
		return R.data(resultMap);
	}

	@ApiOperation("下载人员导入错误数据")
	@PostMapping("/down/err/excel")
	public void downErrExcel(HttpServletResponse response,
							 @ApiParam(value = "人员等级", required = true) @RequestParam("level") Integer level) {
		userService.downErrExcel(response, level);
	}

	@ApiOperation("导出人员")
	@PostMapping("/down/excel/detail")
	public void downExcelDetail(HttpServletResponse response, @RequestBody User user) throws IOException {
		List<List<String>> rows = new ArrayList<>();
		userService.downExcelDetail(user, rows);
		if (Func.isEmpty(rows)) {
			throw new ServiceException("暂无人员数据导出");
		}
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<String> title = CollUtil.newArrayList
				("所属公司", "关联机构（必填）", "姓名（必填）", "手机号（必填）", "性别", "生日", "昵称", "交通工具（必填）", "详细住址（必填）");
			excelWriter = cn.hutool.poi.excel.ExcelUtil.getBigWriter(rows.size());
			excelWriter.setColumnWidth(0, 30);
			excelWriter.setColumnWidth(1, 30);
			excelWriter.setColumnWidth(2, 30);
			excelWriter.setColumnWidth(3, 30);
			excelWriter.setColumnWidth(4, 30);
			excelWriter.setColumnWidth(5, 30);
			excelWriter.setColumnWidth(6, 40);
			excelWriter.setColumnWidth(7, 40);
			excelWriter.setColumnWidth(8, 40);

			// 单独设置头部
			excelWriter.writeHeadRow(title);
			String fileName = cn.hutool.core.date.DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			CommonUtil.setResponseHeader(response, fileName);
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}

	}

}
